// app/controller/procurement/contract_controller.js
'use strict';

const Controller = require('egg').Controller;

class ContractController extends Controller {
  // 获取合同列表
  async index() {
    const { ctx } = this;
    const { supplierId, status, page = 1, limit = 20 } = ctx.query;
    
    try {
      // 构建查询条件
      const whereClause = {};
      if (supplierId) {
        whereClause.supplierId = supplierId;
      }
      if (status) {
        whereClause.status = status;
      }
      
      // 查询数据
      const result = await ctx.model.ContractModel.findAndCountAll({
        where: whereClause,
        include: [{
          model: ctx.model.SupplierModel,
          as: 'supplier',
          attributes: ['id', 'name']
        }],
        order: [['createdAt', 'DESC']],
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit)
      });
      
      // 转换数据格式
      const contracts = result.rows.map(contract => ({
        id: contract.id,
        contractNumber: contract.contractNumber,
        supplierId: contract.supplierId,
        contractName: contract.contractName,
        contractType: contract.contractType,
        startDate: contract.startDate,
        endDate: contract.endDate,
        amount: contract.amount,
        status: contract.status,
        attachment: contract.attachment,
        remark: contract.remark,
        createdAt: contract.createdAt,
        updatedAt: contract.updatedAt,
        supplier: contract.supplier ? {
          id: contract.supplier.id,
          name: contract.supplier.name
        } : null
      }));
      
      ctx.page(contracts, result.count, parseInt(page), parseInt(limit));
    } catch (error) {
      ctx.logger.error('获取合同列表失败:', error);
      ctx.error(`获取合同列表失败: ${error.message}`);
    }
  }
  
  // 获取合同详情
  async show() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const contract = await ctx.model.ContractModel.findByPk(id, {
        include: [{
          model: ctx.model.SupplierModel,
          as: 'supplier',
          attributes: ['id', 'name']
        }]
      });
      
      if (!contract) {
        ctx.error('合同不存在', 404);
        return;
      }
      
      ctx.success({
        id: contract.id,
        contractNumber: contract.contractNumber,
        supplierId: contract.supplierId,
        contractName: contract.contractName,
        contractType: contract.contractType,
        startDate: contract.startDate,
        endDate: contract.endDate,
        amount: contract.amount,
        status: contract.status,
        attachment: contract.attachment,
        remark: contract.remark,
        createdAt: contract.createdAt,
        updatedAt: contract.updatedAt,
        supplier: contract.supplier ? {
          id: contract.supplier.id,
          name: contract.supplier.name
        } : null
      });
    } catch (error) {
      ctx.logger.error('获取合同详情失败:', error);
      ctx.error(`获取合同详情失败: ${error.message}`);
    }
  }
  
  // 创建合同
  async create() {
    const { ctx } = this;
    const contractData = ctx.request.body;
    
    try {
      // 使用Joi验证服务进行参数验证
      const validation = ctx.service.validationService.validateCreateContract(contractData);
      if (validation.error) {
        ctx.error(`参数验证失败: ${validation.error.message}`);
        return;
      }
      
      const { contractNumber, supplierId, contractName, contractType, startDate, endDate, amount, status, attachment, remark } = contractData;
      
      // 检查合同编号是否已存在
      const existingContract = await ctx.model.ContractModel.findOne({
        where: { contractNumber }
      });
      
      if (existingContract) {
        ctx.error('合同编号已存在', 400);
        return;
      }
      
      // 创建合同
      const contract = await ctx.model.ContractModel.create({
        contractNumber,
        supplierId,
        contractName,
        contractType: contractType || 'purchase',
        startDate,
        endDate,
        amount,
        status: status || 'active',
        attachment,
        remark
      });
      
      ctx.success({
        id: contract.id
      }, '合同创建成功');
    } catch (error) {
      ctx.logger.error('创建合同失败:', error);
      ctx.error(`创建合同失败: ${error.message}`);
    }
  }
  
  // 更新合同
  async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const contractData = ctx.request.body;
    
    try {
      // 使用Joi验证服务进行参数验证
      // 首先验证ID
      const idValidation = ctx.service.validationService.validateId(parseInt(id));
      if (idValidation.error) {
        ctx.error(`参数验证失败: ${idValidation.error.message}`);
        return;
      }
      
      // 验证合同数据
      const validation = ctx.service.validationService.validateUpdateContract(contractData);
      if (validation.error) {
        ctx.error(`参数验证失败: ${validation.error.message}`);
        return;
      }
      
      const { contractNumber, supplierId, contractName, contractType, startDate, endDate, amount, status, attachment, remark } = contractData;
      
      const contract = await ctx.model.ContractModel.findByPk(id);
      if (!contract) {
        ctx.error('合同不存在', 404);
        return;
      }
      
      // 检查合同编号是否已存在（排除当前合同）
      if (contractNumber && contractNumber !== contract.contractNumber) {
        const existingContract = await ctx.model.ContractModel.findOne({
          where: { 
            contractNumber,
            id: {
              [ctx.app.Sequelize.Op.ne]: id
            }
          }
        });
        
        if (existingContract) {
          ctx.error('合同编号已存在', 400);
          return;
        }
      }
      
      // 更新合同
      await contract.update({
        contractNumber,
        supplierId,
        contractName,
        contractType,
        startDate,
        endDate,
        amount,
        status,
        attachment,
        remark
      });
      
      ctx.success(null, '合同更新成功');
    } catch (error) {
      ctx.logger.error('更新合同失败:', error);
      ctx.error(`更新合同失败: ${error.message}`);
    }
  }
  
  // 删除合同
  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const contract = await ctx.model.ContractModel.findByPk(id);
      if (!contract) {
        ctx.error('合同不存在', 404);
        return;
      }
      
      // 删除合同
      await contract.destroy();
      
      ctx.success(null, '合同删除成功');
    } catch (error) {
      ctx.logger.error('删除合同失败:', error);
      ctx.error(`删除合同失败: ${error.message}`);
    }
  }
}

module.exports = ContractController;